#include <pthread.h>
#include <string>
#include <ctime>
#include "RingQueue.hpp"
#include <unistd.h>
using namespace std;

struct ThreadData
{
    RingQueue<int> *rq;
    std::string threadname;
};

void *Productor(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        int x = rand() % 10;
        td->rq->Push(x);
        cout << "生产了一个数据:" << x << " who:" << td->threadname << endl;
        // sleep(1);
    }
}

void *Consumer(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    while (true)
    {
        int y = td->rq->Pop();
        cout << "消费了一个数据:" << y << " who:" << td->threadname << endl;
        // fflush(1);
        sleep(1);
    }
}

int main()
{
    srand(time(nullptr));
    RingQueue<int> *rq = new RingQueue<int>();
    pthread_t c[5];
    pthread_t p[3];

    for (int i = 0; i < 3; ++i)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "productor- " + std::to_string(i + 1);
        pthread_create(p + i, nullptr, Productor, td);
    }
    for (int i = 0; i < 5; ++i)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "consumer- " + std::to_string(i + 1);
        pthread_create(c + i, nullptr, Consumer, td);
    }
    for (int i = 0; i < 3; ++i)
    {
        pthread_join(p[i], nullptr);
    }
    for (int i = 0; i < 5; ++i)
    {
        pthread_join(c[i], nullptr);
    }

    return 0;
}